/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jili.ubert.clientapi;

import com.jili.ubert.dao.db.AlterOrder;
import com.jili.ubert.code.client2server.MsgWord;
import com.jili.ubert.code.server2client.MsgResult;
import com.jili.ubert.code.server2client.MsgResultList;
import com.jili.ubert.dao.db.AccountInfo;
import com.jili.ubert.dao.db.TradeReportDetail;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.SynchronousQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author ChengJili
 */
class TradeClientHanlder extends SimpleChannelInboundHandler<MsgEntity> {
    /*
     1区变量
     */

    private final TradeRequest client;
    /*
     2区 构造函数区
     */
    private static final Log log = LogFactory.getLog(TradeClientHanlder.class);
    public TradeClientHanlder(TradeRequest client) {
        this.client = client;
    }
    /*
    final BlockingQueue<String> verlidCodeAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> loginAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> submitAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> commonAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> logoutAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> checkOrderAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResultList> checkOrdersAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResultList> checkBasketOrderAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> checkOrderCAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> checkOrderAAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResultList> newOrdersAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResultList> cancelOrdersAnswer = new SynchronousQueue<>();
    final BlockingQueue<List<PosDetail>> posdetailAnswer = new SynchronousQueue<>();
    final BlockingQueue<List<AccountInfo>> queryAccountListAnswer = new SynchronousQueue<>();
    final BlockingQueue<List<FundState>> queryFundStatusAnswer = new SynchronousQueue<>();
    final BlockingQueue<List<OrderExecuteProgress>> orderStatusAnswer = new SynchronousQueue<>();
    final BlockingQueue<List<TradeReportDetail>> orderReportsAnswer = new SynchronousQueue<>();
    final BlockingQueue<OrderExecuteProgress> orderExeLastStatusAnswer = new SynchronousQueue<>();
    final BlockingQueue<MsgResult> daoAnswer = new LinkedBlockingQueue<>();
    */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        if (ctx.channel().isActive()) {
            ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        } else {
            ctx.close();
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void channelActive(final ChannelHandlerContext ctx) {
        log.info("新增登陆连接：" + ctx.channel());
    }
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MsgEntity msg) throws Exception {
        log.debug("messageReceived验证码为：");
        if (msg == null) {
            return;
        }
        msg.setChannel(ctx.channel());
        // int playerid = ServerCache.get(ctx.channel());
        int csCommondCode = msg.getCmdCode();
        byte[] data = msg.getData();
        int requstid = msg.getSessionID();
        switch (csCommondCode) {
            case 1000: {//base64位解析，fastJSON解析
                ClientAPI.WorkRun(new Runnable(){ 

                    @Override
                    public void run() {
                        client.AccpetSessionAnswer(requstid,msg);
                    }
                });
                break;
            }
            case 1001: {//base64位解析1000的回调
                ClientAPI.WorkRun(new Runnable(){ 

                    @Override
                    public void run() {
                        client.AccpetSessionAnswer(requstid,msg);
                    }
                });
                break;
            }
            case 1002: {//base64位解析
                ClientAPI.WorkRun(new Runnable(){ 

                    @Override
                    public void run() {
                        client.AccpetSessionAnswer(requstid,msg);
                    }
                });
                break;
            }
            case 250:{
                ClientAPI.WorkRun(new Runnable(){ 

                    @Override
                    public void run() {
                        try {
                            MsgResult rst = MsgResult.DeCode(data);
                            client.AccpetSessionFaileAnswer(requstid, rst);
                        } catch (IOException ex) {
                            Logger.getLogger(TradeClientHanlder.class.getName()).log(Level.SEVERE, null, ex);
                        }
                        
                    }
                });
                break;
            }
            default: {
                ClientAPI.WorkRun(new Runnable(){ 

                    @Override
                    public void run() {
                        client.AccpetSessionAnswer(requstid,msg);
                    }
                });
                break;
            }
        }
    }
    /*
     4区 终断，重连，异常处理
     */
    /*
     5区 同步接口封装
     */
    /*
    MsgResult getDAOoperationAnswer() {
        boolean interrupted = false;
        try {
            for (;;) {
                try {
                    return daoAnswer.take();
                } catch (InterruptedException ignore) {
                    interrupted = true;
                }
            }
        } finally {
            if (interrupted) {
                Thread.currentThread().interrupt();
            }
        }
    }
    */
}
